﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using Accountant.DataModel;
using Caliburn.Micro;

namespace Accountant.ViewModels
{
  [Export]
  public sealed class OperationsSource : PropertyChangedBase, IPartImportsSatisfiedNotification
  {
    [Import]
    public AccountantContext Data { get; set; }

    #region ' Account '

    public Account Account
    {
      get { return _account; }
      set
      {
        if (Equals(value, _account)) return;
        _account = value;
        NotifyOfPropertyChange(() => Account);
      }
    }

    private Account _account;

    #endregion

    #region ' Start '

    private DateTime _start = DateTime.MinValue;

    public DateTime Start
    {
      get { return _start; }
      set
      {
        if (value.Equals(_start)) return;
        _start = value;
        NotifyOfPropertyChange(() => Start);
      }
    }

    #endregion

    #region ' Stop '

    private DateTime _stop = DateTime.MaxValue;

    public DateTime Stop
    {
      get { return _stop; }
      set
      {
        if (value.Equals(_stop)) return;
        _stop = value;
        NotifyOfPropertyChange(() => Stop);
      }
    }

    #endregion

    #region ' IncludeDerivedAccounts '

    private bool _includeDerivedAccounts = true;

    public bool IncludeDerivedAccounts
    {
      get { return _includeDerivedAccounts; }
      set
      {
        if (value.Equals(_includeDerivedAccounts)) return;
        _includeDerivedAccounts = value;
        NotifyOfPropertyChange(() => IncludeDerivedAccounts);
      }
    }

    #endregion

    #region  ' ProposedDateFormat '

    private string _proposedDateFormat;

    public string ProposedDateFormat
    {
      get { return _proposedDateFormat; }
      set
      {
        _proposedDateFormat = value;
        ApplyDateFormat();
      }
    }

    private void ApplyDateFormat()
    {
      foreach (var view in Views)
        view.ProposedDateFormat = _proposedDateFormat;
    }

    #endregion

    public ObservableCollection<OperationsViewModel> Views { get; private set; }

    public void Update()
    {
      NotifyOfPropertyChange(() => Account);
    }

    void IPartImportsSatisfiedNotification.OnImportsSatisfied()
    {
      Views = new ObservableCollection<OperationsViewModel>
                {
                  new GenericOperationsViewModel(this),
                  new IncomeOperationsViewModel(this),
                  new ExpenseOperationsViewModel(this),
                  new ExchangeOperationsViewModel(this),
                  new TransferOperationsViewModel(this),
                  new TakeCreditOperationsViewModel(this),
                };     

    }
  }
}
